package com.tianxin.workbao.workBao.Activity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.adapter.SelectCoalAdapter;
import com.tianxin.workbao.workBao.adapter.SelectCoalFactoryAdapter;
import com.tianxin.workbao.workBao.adapter.SelectCustomerAdapter;
import com.tianxin.workbao.workBao.adapter.SelectInputAdapter;
import com.tianxin.workbao.workBao.bean.Coal;
import com.tianxin.workbao.workBao.bean.CoalFactory;
import com.tianxin.workbao.workBao.bean.Customers;
import com.tianxin.workbao.workBao.bean.Inputbill;
import com.tianxin.workbao.workBao.bean.Sampling;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.CoalFactoryProvide;
import com.tianxin.workbao.workBao.dataProvide.CoalProvide;
import com.tianxin.workbao.workBao.dataProvide.CustomerProvide;
import com.tianxin.workbao.workBao.dataProvide.InputProvide;
import com.tianxin.workbao.workBao.dataProvide.SamplingProvide;
import com.tianxin.workbao.workBao.holder.SelectCoalFactoryHolder;
import com.tianxin.workbao.workBao.holder.SelectCoalHolder;
import com.tianxin.workbao.workBao.holder.SelectCustomerHolder;
import com.tianxin.workbao.workBao.holder.SelectInputHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

/**
 * Created by hacker on 2017/7/27.
 */

public class SamplingOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener, MyPopupWindowListener {

    private TextView samplingNumberTV;
    private TextView supplyTV;
    private TextView coalFactoryTV;
    private TextView coalTV;
    private TextView billsTV;
    private TextView selectCarsTV;
    private TextView selectWeightTV;
    private Button resetBtn;
    private Button selectBtn;
    private FloatingActionButton saveFab;

    private String samplingNumber;
    private Sampling mSampling;
    private int companyType = Constant.CUSTOMER_TYPE_SALE;

    private CoalProvide coalProvide;
    private CustomerProvide customerProvide;
    private InputProvide inputProvide;
    private SamplingProvide samplingProvide;
    private CoalFactoryProvide coalFactoryProvide;
    private String billIds;
    private String billNumbers;
    private String carNumbers;
    private Float mWeight;
    private int cars;
    private List<Coal> mCoalList;
    private List<Customers> mCustomerList;
    private List<Inputbill> mInputList;
    private List<CoalFactory> mCoalFactoryList;
    private PopupWindow popupWindow;

    private final int POPUP_TYPE_COAL = 0;
    private final int POPUP_TYPE_CUSTOMER = 1;
    private final int POPUP_TYPE_INPUT = 2;
    private final int POPUP_TYPE_FACTORY = 3;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampling_option);

        initView();
        initData();
        initEvent();
        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(R.string.sampling);
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        setSupportActionBar(mToolbar);

        samplingNumberTV = (TextView) findViewById(R.id.number);
        supplyTV = (TextView) findViewById(R.id.supply);
        coalFactoryTV = (TextView) findViewById(R.id.coal_factory);
        coalTV = (TextView) findViewById(R.id.coal);
        billsTV = (TextView) findViewById(R.id.bills);
        selectCarsTV = (TextView) findViewById(R.id.select_cars);
        selectWeightTV = (TextView) findViewById(R.id.select_weight);
        resetBtn = (Button) findViewById(R.id.reset_btn);
        selectBtn = (Button) findViewById(R.id.select_btn);
        saveFab = (FloatingActionButton) findViewById(R.id.save_fab);
    }

    @Override
    public void initData() {
        initSamplingNumber();
        mSampling = new Sampling();
        mSampling.setSbtype(1);
        mSampling.setSbnum(samplingNumber);
        mSampling.setAddtime(new Date());
        mSampling.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mSampling.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));
        mSampling.setSamplingtime(mSampling.getAddtime());
        mSampling.setSamplinguid(mSampling.getAdduserid());
        mSampling.setSamplinguname(mSampling.getAddusername());
        mSampling.setIsis(1);
        mSampling.setIstest(0);
        mSampling.setRemark("手机录入");
    }

    /**
     * initialing sampling number
     */
    private void initSamplingNumber() {
        samplingNumber = BeansUtil.getNumber(Constant.SAMPLING_HEADER);
    }

    @Override
    public void initEvent() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SamplingOptionActivity.this.finish();
            }
        });
        resetBtn.setOnClickListener(this);
        selectBtn.setOnClickListener(this);
        saveFab.setOnClickListener(this);
        supplyTV.setOnClickListener(this);
        coalTV.setOnClickListener(this);
        coalFactoryTV.setOnClickListener(this);
    }

    @Override
    public void bindView() {
        samplingNumberTV.setText(samplingNumber);
        billsTV.setText("");
    }

    //View.OnClickListener
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //save sampling to server and local db
            case R.id.save_fab:
                saveSampling();
                break;
            //reset bills
            case R.id.reset_btn:
                resertSelectData();
                break;
            //select bills
            case R.id.select_btn:
                getInputList();
                break;
            //select coals
            case R.id.coal:
                getCoalList();
                break;
            //select supply
            case R.id.supply:
                this.companyType = Constant.CUSTOMER_TYPE_SALE;
                getCustomerList();
                break;
            case R.id.coal_factory:
                getCoalFactoryList();
                break;
        }
    }

    /**
     * save the sampling
     */
    private void saveSampling() {
        if (mSampling == null) {
            showMessage("采样数据异常");
            return;
        }
        if (mSampling.getSupplycpid() == null || mSampling.getCoaltypeid() == null) {
            showMessage("选择供应商或煤种");
            return;
        }
        if (mSampling.getWeighbillids() == null || mSampling.getWeighbillnums() == null || cars < 1) {
            showMessage("选择磅单出错");
            return;
        }
        if (mSampling.getCoalfactoryid() == null || mSampling.getCoalfactoryid() < 1) {
            showMessage("选择货场出错");
            return;
        }
        // save
        getSamplingProvide().saveSampling(mSampling);
    }

    private void getCoalList() {
        getCoalProvide().getAllCoals();
    }

    private void getInputList() {
        if (mSampling != null
                && mSampling.getSupplycpid() != null
                && mSampling.getSupplycpid() > 0
                && mSampling.getCoaltypeid() != null
                && mSampling.getCoaltypeid() > 0
                ) {
            getInputProvide().getNoSampling(mSampling.getSupplycpid(), mSampling.getCoaltypeid());
        } else {
            showMessage("请先选择供应商和煤种");
            return;
        }


    }

    private void getCustomerList() {
        getCustomerProvide().getAllCustomers(companyType);
    }

    private void getCoalFactoryList() {
        getCoalFactoryProvide().getdata();
    }

    @Override
    public void OnMyClick(Integer selectType, Integer id, String information) {

        switch (selectType) {
            case Constant.SELECT_TYPE_COAL:
                dismissPoPup();
                mSampling.setCoaltypeid(id);
                mSampling.setCoaltype(information);
                coalTV.setText(information);
                break;
            case Constant.SELECT_TYPE_CUSTOMER:
                dismissPoPup();
                mSampling.setSupplycpid(id);
                mSampling.setSupplycpname(information);
                supplyTV.setText(information);
                break;
            case Constant.SELECT_TYPE_INPUT:
                if (id == -1) {
                    showMessage("点击返回出错！");
                    resertSelectData();
                    dismissPoPup();
                    return;
                }
                try {
                    JSONObject object = new JSONObject(information);
                    String contractId = object.getString("contractId");
                    String contractNum = object.getString("contractNumber");
                    if (contractId.length() < 1 || contractNum.length() < 1) {
                        showMessage("所关联的过磅数据没有合同");
                        resertSelectData();
                        dismissPoPup();
                        return;
                    }
                    if (mSampling.getContractid() != null) {
                        if (mSampling.getContractid() != Integer.valueOf(contractId)) {
                            showMessage("所关联的过磅数据的合同存在多个合同");
                            resertSelectData();
                            dismissPoPup();
                            return;
                        }
                    } else {
                        mSampling.setContractid(Integer.valueOf(contractId));
                        mSampling.setCtnum(contractNum);
                    }
                    String tempId = object.getString("id");
                    if (billIds == null || billIds.length() == 0) {
                        billIds = tempId;
                    } else {
                        billIds = billIds + "," + tempId;
                    }
                    mSampling.setWeighbillids(billIds);
                    String tempNumber = object.getString("number");
                    if (billNumbers == null || billNumbers.length() == 0) {
                        billNumbers = tempNumber;
                    } else {
                        billNumbers = billNumbers + "," + tempNumber;
                    }
                    mSampling.setWeighbillnums(billNumbers);
                    String tempWeight = object.getString("weight");
                    if (mWeight == null || mWeight < 0) {
                        mWeight = Float.valueOf(tempWeight);
                    } else {
                        mWeight = mWeight + Float.valueOf(tempWeight);
                    }
                    mSampling.setWeights(mWeight);
                    selectWeightTV.setText(mWeight + "");
                    cars++;
                    mSampling.setWeightscarnum(cars);
                    selectCarsTV.setText(cars + "");

                    String tempCarNumber = object.getString("carNumber");
                    if (carNumbers == null || carNumbers.length() == 0) {
                        carNumbers = tempCarNumber;
                    } else {
                        carNumbers = carNumbers + "," + tempNumber;
                    }
                    mSampling.setCarnumbers(carNumbers);
                    String replace = billsTV.getText().toString();
                    if (replace.length() < 1) {
                        replace = object.getString("number")
                                + "  " + object.getString("carNumber")
                                + " " + object.getString("weight") + "吨";
                    } else {
                        replace = replace + "\n" + object.getString("number")
                                + "  " + object.getString("carNumber")
                                + " " + object.getString("weight") + "吨";
                    }
                    billsTV.setText(replace);
                } catch (JSONException e) {
                    showMessage("点击返回出错");
                    resertSelectData();
                    dismissPoPup();
                    e.printStackTrace();
                }
                break;
            case Constant.SELECT_TYPE_FACTORY:
                dismissPoPup();
                mSampling.setCoalfactoryid(id);
                mSampling.setCoalfactory(information);
                coalFactoryTV.setText(information);
                break;
        }
    }

    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            this.finish();
        } else if (msg.contains("failure")) {
            Toast.makeText(this, "采样单录入失败！\n " + msg.substring(msg.indexOf("failure") + 1, msg.length()), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("",2000);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List) {
            if (((List) result).size() > 0) {
                if (((List) result).get(0) instanceof Coal) {
                    mCoalList = (List<Coal>) result;
                    if (mCoalList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_COAL);
                    }
                } else if (((List) result).get(0) instanceof Customers) {
                    mCustomerList = (List<Customers>) result;
                    if (mCustomerList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_CUSTOMER);
                    }
                } else if (((List) result).get(0) instanceof Inputbill) {
                    mInputList = (List<Inputbill>) result;
                    if (mInputList != null) {
                        showSelectPopup(POPUP_TYPE_INPUT);
                    }
                } else if (((List) result).get(0) instanceof CoalFactory) {
                    mCoalFactoryList = (List<CoalFactory>) result;
                    if (mCoalFactoryList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_FACTORY);
                    } else {
                        showMessage("无法获取货场信息");
                    }
                }
            }

        } else {
            showMessage("response other information");
        }
    }

    private void showSelectPopup(int type) {
        popupWindow = new PopupWindow();
        switch (type) {
            case POPUP_TYPE_COAL:
                SelectCoalAdapter selectCoalAdapter = new SelectCoalAdapter(mCoalList, this, this);
                SelectCoalHolder selectCoalHolder = new SelectCoalHolder(this, this, selectCoalAdapter);
                popupWindow.setContentView(selectCoalHolder.getContentView());
                popupWindow.setHeight(340);
                break;
            case POPUP_TYPE_CUSTOMER:
                SelectCustomerAdapter selectCustomerAdapter = new SelectCustomerAdapter(mCustomerList, this, this);
                SelectCustomerHolder selectCustomerHolder = new SelectCustomerHolder(this, this, selectCustomerAdapter);
                popupWindow.setContentView(selectCustomerHolder.getContentView());
                popupWindow.setHeight(400);
                break;
            case POPUP_TYPE_INPUT:
                SelectInputAdapter selectInputAdapter = new SelectInputAdapter(mInputList, this, this);
                SelectInputHolder selectInputHolder = new SelectInputHolder(this, this, selectInputAdapter);
                popupWindow.setContentView(selectInputHolder.getContentView());
                popupWindow.setHeight(400);
                break;
            case POPUP_TYPE_FACTORY:
                SelectCoalFactoryAdapter selectCoalFactoryAdapter = new SelectCoalFactoryAdapter(mCoalFactoryList, this, this);
                SelectCoalFactoryHolder selectCoalFactoryHolder = new SelectCoalFactoryHolder(this, this, selectCoalFactoryAdapter);
                popupWindow.setContentView(selectCoalFactoryHolder.getContentView());
                popupWindow.setHeight(200);
                break;
            default:
                return;
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.write)));
        popupWindow.setAnimationStyle(R.style.my_popup_animation_style);
        popupWindow.showAtLocation(mToolbar, Gravity.TOP, 0, 0);
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    public CoalProvide getCoalProvide() {
        if (coalProvide == null) {
            coalProvide = new CoalProvide(this, this);
        }
        return coalProvide;
    }

    public CustomerProvide getCustomerProvide() {
        customerProvide = new CustomerProvide(this, this, this.companyType);
        return customerProvide;
    }

    public InputProvide getInputProvide() {
        if (inputProvide == null) {
            inputProvide = new InputProvide(this, this);
        }
        return inputProvide;
    }

    public SamplingProvide getSamplingProvide() {
        if (samplingProvide == null) {
            samplingProvide = new SamplingProvide(this, this, false);
        }
        return samplingProvide;
    }

    public CoalFactoryProvide getCoalFactoryProvide() {
        if (coalFactoryProvide == null) {
            coalFactoryProvide = new CoalFactoryProvide(this, this);
        }
        return coalFactoryProvide;
    }

    private void dismissPoPup() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    private void resertSelectData() {
        cars = 0;
        selectCarsTV.setText("0");
        mWeight = Float.valueOf("0");
        selectWeightTV.setText("0");
        billIds = "";
        billNumbers = "";
        billsTV.setText("");
        carNumbers = "";
        coalFactoryTV.setText("");
    }
}
